package com.wwwarehouse.usercenter.fragment.chain_triangles;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.popupwindow.EasyPopupWindow;
import com.wwwarehouse.common.eventbus_event.BackListenerEvent;
import com.wwwarehouse.common.eventbus_event.CardDeskEvent;
import com.wwwarehouse.common.eventbus_event.GiveOnLineEvent;
import com.wwwarehouse.common.eventbus_event.TCEvent;
import com.wwwarehouse.common.tools.ApkTools;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.bean.chain_triangles.ScanCodeBean;
import com.wwwarehouse.usercenter.bean.response.InviteInfoResponseBean;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;

import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2016/11/7.
 */

@Route(path = UserCenterConstant.PATH_TC_SUCCESS_FRAGMWNT)
public class TCSuccessFragment extends BaseFragment implements View.OnClickListener {

    private View mView;

    private ImageView mTcSuccessIv;//图标
    private TextView mTcAdministratorSuccessTv;//成功标题
    private RelativeLayout mTcAddressBookInstationRl;//站内通讯录显示的内容
    private ProgressBar mTcVerifyLoginPb;//查询是否是登录状态的时候显示
    private TextView mTcVerifyLoginDefeatedTv;//内容（站内通讯录）
    private ImageView mTcMarkIv;//图片（站内通讯录）
    private LinearLayout mTcCallLl;//联系TA（站内通讯录）
    private LinearLayout mTcOtherContentLl;//其他显示的内容
    private TextView mLine1Tv;//第一行（其他）
    private TextView mLine2Tv;//第二行（其他）
    private Button mSureBtn;//按钮

    private EasyPopupWindow mEasyPopupWindow;
    private int type;
    private String message;
    private CountDownTimer mCountDownTimer;
    private InviteInfoResponseBean.InviteDetailsBean mInviteDetailsBean;
    private int from;//0建立1管理

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = View.inflate(getActivity(), R.layout.fragment_tc_success, null);
        return mView;
    }



    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initEvent();
    }

    private void initView() {
        mTcSuccessIv = (ImageView) mView.findViewById(R.id.tc_success_iv);
        mTcAdministratorSuccessTv = (TextView) mView.findViewById(R.id.tc_administrator_success_tv);
        mTcAddressBookInstationRl = (RelativeLayout) mView.findViewById(R.id.tc_address_book_instation_rl);
        mTcOtherContentLl = (LinearLayout) mView.findViewById(R.id.tc_other_content_ll);
        mTcVerifyLoginPb = (ProgressBar) mView.findViewById(R.id.tc_verify_login_pb);
        mTcVerifyLoginDefeatedTv = (TextView) mView.findViewById(R.id.tc_verify_login_defeated_tv);
        mTcMarkIv = (ImageView) mView.findViewById(R.id.tc_mark_iv);
        mTcCallLl = (LinearLayout) mView.findViewById(R.id.tc_call_ll);
        mLine1Tv = (TextView) mView.findViewById(R.id.line1_tv);
        mLine2Tv = (TextView) mView.findViewById(R.id.line2_tv);
        mSureBtn = (Button) mView.findViewById(R.id.sure_btn);
    }

    private void initEvent() {
        mTcCallLl.setOnClickListener(this);
        mSureBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tc_call_ll) {
            callTa();
        } else if (v.getId() == R.id.sure_btn) {
            if (type == Constant.TYPE_SCAN_CODE) {
                popFragment();
                return;
            }
            if (TriangulationChainFragment.hasAT_SV()) {
                EventBus.getDefault().post(new CardDeskEvent("clear_back_stack"));
            } else {
                EventBus.getDefault().post(new TCEvent(""));
                popFragment();
            }
        }
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof TCSuccessFragment) {
            mActivity.setTitle(getResources().getString(R.string.set_triangular_management));
        }
    }

    @Override
    public void requestDatas() {
        EventBus.getDefault().register(this);
        type = getArguments().getInt("type");
        from = getArguments().getInt("from", 0);
        if (type == Constant.TYPE_F2F) {
            mTcAddressBookInstationRl.setVisibility(View.GONE);
            mTcOtherContentLl.setVisibility(View.VISIBLE);
            message = getArguments().getString("message");
            ScanCodeBean scanCodeBean = JSON.parseObject(message, ScanCodeBean.class);
//            mTcAdministratorSuccessTv.setText("指定成功");
            mTcAdministratorSuccessTv.setText(scanCodeBean.getMsg().getMessageType());
            int endIndex = scanCodeBean.getMsg().getMessage().length();
            if (scanCodeBean.getMsg().getMessage().indexOf("，") != 0) {
                endIndex = scanCodeBean.getMsg().getMessage().indexOf("，") + 1;
            }
            mLine1Tv.setText(scanCodeBean.getMsg().getMessage().substring(0, endIndex));
            if (endIndex != scanCodeBean.getMsg().getMessage().length())
                mLine2Tv.setText(scanCodeBean.getMsg().getMessage().substring(endIndex));
            if (TriangulationChainFragment.hasAT_SV()) {
                mSureBtn.setText(getResources().getString(R.string.return_desk));
            } else {
//                if (from == 0) {
//                    mSureBtn.setText("返回建立三角链任务");
//                } else {
//                    mSureBtn.setBackground(getResources().getDrawable(R.drawable.common_btn6_selector));
//                    mSureBtn.setText("返回管理三角链任务");
//                }
                mSureBtn.setBackground(getResources().getDrawable(R.drawable.common_btn6_selector));
                mSureBtn.setText(getResources().getString(R.string.return_set_triangle_management));
            }
        } else if (type == Constant.TYPE_SCAN_CODE) {
            mTcAddressBookInstationRl.setVisibility(View.GONE);
            mTcOtherContentLl.setVisibility(View.VISIBLE);
            mTcAdministratorSuccessTv.setText(getResources().getString(R.string.specify_success));
            if (getArguments().getString(Constant.KEY_SECURITY_QR_CODE).length() > 12) {
                mLine1Tv.setText(getArguments().getString(Constant.KEY_SECURITY_QR_CODE).substring(0, 12));
                mLine2Tv.setText(getArguments().getString(Constant.KEY_SECURITY_QR_CODE).substring(12));
            } else {
                mLine1Tv.setText(getArguments().getString(Constant.KEY_SECURITY_QR_CODE));
            }
            mSureBtn.setText(getResources().getString(R.string.i_know));
        } else if (type == Constant.TYPE_ADDRESS) {
            mInviteDetailsBean = (InviteInfoResponseBean.InviteDetailsBean) getArguments().getSerializable("bean");
            mTcVerifyLoginPb.setVisibility(View.VISIBLE);
            mCountDownTimer = new CountDownTimer(5000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    mTcVerifyLoginPb.setVisibility(View.VISIBLE);
                    mTcVerifyLoginDefeatedTv.setVisibility(View.INVISIBLE);
                }

                @Override
                public void onFinish() {
                    mTcVerifyLoginPb.setVisibility(View.INVISIBLE);
                    mTcVerifyLoginDefeatedTv.setVisibility(View.VISIBLE);
                    mTcVerifyLoginDefeatedTv.setText(getResources().getString(R.string.not_login_status));
                }
            };
            mCountDownTimer.start();

            mTcAddressBookInstationRl.setVisibility(View.VISIBLE);
            mTcOtherContentLl.setVisibility(View.INVISIBLE);
            mTcAdministratorSuccessTv.setText(getResources().getString(R.string.specify_success));
            if (TriangulationChainFragment.hasAT_SV()) {
                mSureBtn.setText(getResources().getString(R.string.return_desk));
            } else {
//                if (from == 0) {
//                    mSureBtn.setText("返回建立三角链任务");
//                } else {
//                    mSureBtn.setBackground(getResources().getDrawable(R.drawable.common_btn6_selector));
//                    mSureBtn.setText("返回管理三角链任务");
//                }
                mSureBtn.setBackground(getResources().getDrawable(R.drawable.common_btn6_selector));
                mSureBtn.setText(getResources().getString(R.string.return_set_triangle_management));
            }
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mCountDownTimer != null)
            mCountDownTimer.cancel();
    }

    private void callTa() {
        mEasyPopupWindow = PopUpUtils.showPopUpBottom(R.layout.layout_contact_person, getContext(), mActivity.findViewById(android.R.id.content), true, childClickListener);

    }

    EasyPopupWindow.ChildClickListener childClickListener = new EasyPopupWindow.ChildClickListener() {
        @Override
        public void getChildView(int layoutId, View view) {
            view.findViewById(R.id.btn_wechat_contact).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        if (!ApkTools.isWeixinInstall(mActivity)) {
                            toast(getResources().getString(R.string.no_wechat));
                        } else {
                            ApkTools.launchWechat(mActivity);
                        }
                    } catch (Exception e) {
                        toast(getResources().getString(R.string.no_wechat));
                    }
                }
            });

            view.findViewById(R.id.btn_phone_contact).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mInviteDetailsBean.getInviteeMobile()));
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    startActivity(intent);
                }
            });

            view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mEasyPopupWindow.dismiss();
                }
            });
        }
    };


    //通讯录指定成功推送
    public void onEventMainThread(GiveOnLineEvent event) {
        String message = event.getResult();
        mCountDownTimer.cancel();
        mTcVerifyLoginPb.setVisibility(View.INVISIBLE);
        mTcVerifyLoginDefeatedTv.setVisibility(View.INVISIBLE);
    }

    public void onEventMainThread(BackListenerEvent event) {
        String message = event.getMsg();
        if (message.equals("TCSuccessFragment")) {
            if (peekFragment() instanceof TCSuccessFragment) {
                    if (type == Constant.TYPE_SCAN_CODE) {
                        popFragment();
                        return;
                    }
                if (TriangulationChainFragment.hasAT_SV()) {
                    EventBus.getDefault().post(new CardDeskEvent("clear_back_stack"));
                } else {
                    EventBus.getDefault().post(new TCEvent(""));
                    popFragment();
                }
            }
        }
    }
}
